<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        
    </style>
</head>
<body>
    用户名：<input type="text" id="username"><br>
    密码：<input type="text" id="password"><br>
    <input type="button" value="get登录" id="btn1">
    <input type="button" value="post注册" id="btn2">
</body>
<script>
    
    const oun = document.getElementById("username")
    const opw = document.getElementById("password")
    const ob1 = document.getElementById("btn1")
    const ob2 = document.getElementById("btn2")

    ob1.onclick = function(){
        ajax({
            url: "http://localhost:3000/login",
            data:{
                username: oun.value,
                password: opw.value
            },
            success:res=>{
                console.log("success", res);
            },
            error:code=>{
                console.log("error", code);
            },
            timeout: 30
        })
    }

    ob2.onclick = function(){
        ajax({
            type:"post",
            url: "http://localhost:3000/register",
            data:{
                username: oun.value,
                password: opw.value
            },
            success:res=>{
                console.log("success", res);
            },
            error:code=>{
                console.log("error", code);
            },
            timeout: 30
        })
    }

    function ajax(ops={}){
        let {type="get", success, error, url, data={}, timeout=100} = ops;
        // 1. 解析要发送的数据
        let str = "";
        for(let i in data){
            str += `${i}=${data[i]}&`;
        }
        // 2. 判断请求方式决定是否拼接到url
        url = type==="get" ? url+"?"+str.slice(0,-1) : url;
        // 3. 开启ajax
        const xhr = new XMLHttpRequest();

        // 主动设置xhr的最大请求时间，当该时间内未得到响应，触发timeout事件
        xhr.timeout = timeout;

        xhr.open(type, url, true);
        xhr.onload = function(){
            if(xhr.status === 200){
                if(success) success(xhr.responseText);
                // success = error = null;
            }else{
                if(error) error(xhr.status);
                // success = error = null;
            }
        }

        // 绑定xhr的超时事件
        xhr.ontimeout = function(){
            if(error) error("timeout");
            // 终止xhr请求
            xhr.abort();
        }

        // 4. 根据请求方式，决定send的格式和内容
        if(type === "post"){
            xhr.setRequestHeader( "Content-type", "application/x-www-form-urlencoded" );
            xhr.send( str.slice(0,-1) );
        }else{
            xhr.send();
        }

        // setTimeout(()=>{
        //     if(error) error("timeout");
        //     success = error = null;
        // }, timeout);
    }


</script>
</html>